<template>
  <div>
  <el-form ref="form" v-loading="loading" label-position="right" label-width="100px" :rules="rules" :model="form">
    <el-row>
      <el-col :span="12">
        <el-form-item label="处方名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入处方名称"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="添加人" prop="doctor_name">
          <el-input v-model="form.doctor_name" placeholder="请输入添加人"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="症状描述" prop="msg">
          <el-input v-model="form.msg" type="textarea" placeholder="请输入症状描述"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="总价:">
          <span style="color: #1890ff;font-weight: bold;font-size: 16px;"> {{ totalPrice }} 元</span>
        </el-form-item>
      </el-col>

      <el-col :span="24">
        <el-form-item label="药品名">
          <el-input v-model="drugSelect.title" placeholder="请输入药品名" style="width: 32%;"></el-input>
          <el-select v-model="drugSelect.m_type" placeholder="请选择药品类型" style="width: 32%;margin: 0 10px;">
            <el-option label="药品类型" value="0"></el-option>
            <el-option
                v-for="(item,index) in m_arr"
                :key="index"
                :label="item"
                :value="index">
              </el-option>
            </el-select>
          <el-select v-model="drugSelect.u_type" placeholder="请选择使用类型" style="width: 32%;">
            <el-option label="使用类型" value="0"></el-option>
            <el-option
                v-for="(item,index) in u_arr"
                :key="index"
                :label="item"
                :value="index">
              </el-option>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="24">
        <el-form-item label="处方" prop="chufang">
          <el-button type="primary" plain @click="drugAdd">添加药品</el-button>
        </el-form-item>
      </el-col>

      <div v-for="(item,index) in form.drug" :key="index" style="padding-left: 50px;display: inline-block;">
         <div style="padding-left: 50px;">
            <el-checkbox v-model="item.checked" @input="inputOnInput($event)"> {{ item.title }}</el-checkbox>
            <el-button type="text" style="color: #F56C6C;margin-left: 20px;" @click="drugDelete(index)">删除</el-button>
         </div>
         <el-col :span="12">
           <el-form-item label="数量" :prop="`drug[${index}][use_type]`" :rules="rules.num">
             <el-input v-model="item.num" type="number" placeholder="请输入数量" style="width: 80%;" @input="inputOnInput($event)" @change="drugNumChange"></el-input> {{ item.unit }}
           </el-form-item>
         </el-col>
         <el-col :span="6" >
           <el-form-item label="规格:" label-width="70px">
              <div style="height: 33px;"> {{ item['spec'] }}</div>
           </el-form-item>
         </el-col>
         <el-col :span="6" >
           <el-form-item label="单价:" label-width="45px">
              <div style="height: 33px;"> {{ item['sell_price'] }} 元</div>
           </el-form-item>
         </el-col>
         <el-col :span="12">
           <el-form-item label="药品类型" :prop="`drug[${index}][use_type]`" :rules="rules.use_type">
             <el-input v-model="item.use_type" @input="inputOnInput($event)"></el-input>
           </el-form-item>
         </el-col>
         <el-col :span="12">
           <el-form-item label="服用方法" :prop="`drug[${index}][func]`" :rules="rules.func">
             <el-input v-model="item.func" @input="inputOnInput($event)"></el-input>
           </el-form-item>
         </el-col>
         <el-col :span="12">
           <el-form-item label="每次用量" :prop="`drug[${index}][use_num]`" :rules="rules.use_num">
             <el-input v-model="item.use_num" placeholder="片/粒/包/ml" @input="inputOnInput($event)"></el-input>
           </el-form-item>
         </el-col>
         <el-col :span="12">
           <el-form-item label="次数" :prop="`drug[${index}][use_times]`" :rules="rules.use_times">
             <el-input v-model="item.use_times" placeholder="早/中/晚" @input="inputOnInput($event)"></el-input>
           </el-form-item>
         </el-col>
         <el-col :span="12">
           <el-form-item label="服药时间" :prop="`drug[${index}][qianhou]`" :rules="rules.qianhou">
             <el-input v-model="item.qianhou" placeholder="饭前半小时" @input="inputOnInput($event)"></el-input>
           </el-form-item>
         </el-col>
      </div>

    </el-row>
    <el-form-item class="contacts-add">
      <el-button type="primary" @click="onSubmit">提交</el-button>
      <el-button @click="cancle">关闭</el-button>
    </el-form-item>
  </el-form>
  <el-dialog
    title="药品信息"
    :visible.sync="dialogDrugVisible"
    :close-on-click-modal="false"
    width="700px"
    append-to-body>
    <medicine-select v-if="dialogDrugVisible" :data="ruleForm" @cancle="dialogDrugVisible = false" @load="setSelect"></medicine-select>
  </el-dialog>
</div>
</template>

<script>
import * as APIMedicalCare from '@/api/medicalCare';
import { mapState } from 'vuex'
import { unixToDate } from "@/utils";
import medicineSelect from './medicine-select';
export default {
  name: 'MedicineAdd',
  components: {
    medicineSelect
  },
  props: {
    data: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    const checkValidator = (rule, value, callback) => {
       const index = rule.field.split('').findIndex(item => /[0-9]/.test(item))
       const obj = this.form['drug'][rule.field[index]]
      if (obj['checked'] && !obj[rule.type]) {
        callback(new Error('最大单量不能为空'))
      } else {
        callback()
      }
    }
    return {
      form: {},
      // 站点列表
      m_arr: {},   // 药品类型
      u_arr: {},   // 用法类型
      uf_arr: {},  // 使用方法
      drug:[],
      drugSelect:{
        'title': '', // 药品名称 1
        'm_type': "0", //药品类型  1
        'u_type': "0", //用法类型 1
      },
      dialogDrugVisible: false,
      loading: false,
      ruleForm:{},
      totalPrice: 0,
      // 表单校验
      rules: {
        name: [
          { required: true,  message: '请输入处方名称', trigger: 'blur'  }
        ],
        doctor_name: [
          { required: true, message: '请输入添加人',trigger: 'blur' }
        ],
        msg: [
          { required: true, message: '请输入症状描述',  trigger: 'blur' }
        ],
        chufang: [
          { required: true, message: '请添加药品',  trigger: 'blur' }
        ],
        num: [
          { required: true,validator: checkValidator, message: '请输入数量', type:'num', trigger: 'blur' }
        ],
        use_type: [
          { required: true, validator: checkValidator, message: '请输入药品类型', type:'use_type', trigger: 'blur' }
        ],
        func: [
          { required: true, validator: checkValidator, message: '请输入服用方法', type:'func', trigger: 'blur' }
        ],
        use_num: [
          { required: true, validator: checkValidator, message: '请输入每次用量', type:'use_num', trigger: 'blur' }
        ],
        use_times: [
          { required: true, validator: checkValidator, message: '请输入次数', type:'use_times', trigger: 'blur' }
        ],
        qianhou: [
          { required: true, validator: checkValidator, message: '请输入服药时间', type:'qianhou', trigger: 'blur' }
        ],
      }
    }
  },
  watch: {
    data: {
      handler (newval) {
        this.medicineGetarr();
        if(newval.hasOwnProperty('id')){
           // this.getMedicineInfo(newval['id'])
        } else {
           this.form = { ...newval,...{drug:[], chufang:'1' } };
        }
      },
      // 可以一进页面就触发监听器  监听器自带的immediate
      immediate: true,
      deep: true
    }
  },
  mounted () {
     // this.medicineGetarr()
  },
  methods: {
    medicineGetarr(){
      const self = this;
      APIMedicalCare.medicineGetarr().then((resp) => {
         const res = resp.data;
         self['m_arr'] = res['m_arr'];
         self['u_arr'] = res['u_arr'];
         self['uf_arr'] = res['uf_arr'];
      }).finally(() => {
        this.loading = false
      });
    },
    drugAdd(){
      this.ruleForm = { ...this.drugSelect };
      this.dialogDrugVisible = true;
    },
    drugDelete(itemIndex){
      this.form.drug.splice(itemIndex, 1);
      this.drugNumChange();
    },
    drugNumChange(){
       const self = this;
       self.totalPrice = 0;
       self.form.drug.forEach(item =>{
         self.totalPrice += item['num'] * item['sell_price']
       })
       // console.log(self.totalPrice)
    },
    setSelect(row){
      const self = this;
      const filterSelect = self.form.drug.filter(num => num.id == row.id);
      if(filterSelect.length){
        this.$message({ type: "warning", message: "当前药品已存在!"});
        return false;
      }
      row.checked = true;
      row.num = 1;  // 数量
      row['use_type'] = self['u_arr'][Number(row.u_type)];  // 药品类型
      row['func'] = self['uf_arr'][Number(row.u_func)];  // 服用方法
      row['use_num'] = '';  // 每次用量
      row['use_times'] = '';  // 次数
      row['qianhou'] = '';  // 服药时间
      self.form.drug.push(row);
      this.drugNumChange();
    },
    inputOnInput(e){
      this.$forceUpdate()
    },
    onSubmit () {
      const self = this;
      const selectDrug = self.form.drug.filter(item => item['checked']);
      console.log(selectDrug)
      if(selectDrug.length == 0){
        this.form['chufang'] = ''
      } else {
        this.form['chufang'] = '1'
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          const chufangForm = {
             'name': self.form['name'],//处方名称
             'doctor_name': self.form['doctor_name'],//添加人
             'msg': self.form['msg'],//症状描述
          }
          let objDrug = { code_id: [], code_name: [], code: [], num: [],unit: [],use_type: [],func: [],use_num: [],use_times: [],qianhou: []};

           self.form.drug.forEach(item =>{
             if(item['checked']){
               objDrug['code_id'].push(item['id']) //药品id
               objDrug['code_name'].push(item['title']) //药品名称
               objDrug['code'].push(item['code']) //批准文号

               objDrug['num'].push(item['num']) //数量
               objDrug['unit'].push(item['unit']) //规格
               objDrug['use_type'].push(item['use_type']) //药品类型

               objDrug['func'].push(item['func']) //服用方法
               objDrug['use_num'].push(item['use_num']) //每次用量
               objDrug['use_times'].push(item['use_times']) //次数

               objDrug['qianhou'].push(item['use_times']) //服药时间
             }
           })
           for(let objItem in objDrug){
             chufangForm[objItem] = objDrug[objItem].join(',')
           }
          APIMedicalCare.chufangAdd(chufangForm).then(res => {
            this.$message({ type: "success", message: "新增成功!"});
            this.cancle()
            this.load()
          })
        }
      })
    },
    load () {
      this.$emit('load')
    },
    cancle () {
      this.$refs.form.resetFields()
      this.$emit('cancle')
    }
  }
}
</script>

<style lang="scss">
.contacts-add {
  text-align: right;
}
.contract-text {
  font-size: 12px;
  color: #999;
  line-height: 12px;
  margin: 0;
}
.contract-img {
  width: 146px;
  height: 146px;
  cursor: pointer;
}
</style>
